using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.interfaces;
using umbraco.presentation.cache;
using umbraco.uicontrols;
using umbraco.controls;
using Commerce.Common;
using Commerce.Promotions;
using System.Text.RegularExpressions;

namespace CommerceForUmbraco.adminSection.commerce
{
    public partial class editProduct : umbraco.BasePages.UmbracoEnsuredPage
    {
        #region properties

        public TabPage MainTab;
        public TabPage CategoryTab;
        public TabPage ImageTab;
        public TabPage DescriptorTab;
        public TabPage AttributeTab;
        public TabPage CrossSellTab;
        public TabPage ProductDescriptionTab;
        public TabPage ProductOptionsTab;

        //Media Pickers
        private umbraco.editorControls.mediaChooser _mediaPicker;
        private MediaPickerDataExtractor _mediaPickerExtractor;
        private umbraco.editorControls.mediaChooser _otherImagesMediaPicker;
        private MediaPickerDataExtractor _otherImagesMediaPickerExtractor;
        private umbraco.editorControls.tinyMCE3.TinyMCE _tinymce = null;

        // Product
        Product thisProduct;

        #endregion


        protected string GenerateUrlFriendlyName(string name)
        {
            string slug;

            slug = Regex.Replace(name, @"[\?\!:\$""&']", String.Empty);

            slug = Regex.Replace(slug, @"[\.]", "_");

            slug = slug.Replace(' ', '-');

            return slug;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string productId = Request.QueryString.Get("p");
            thisProduct = new Product(int.Parse(productId));

            if (!IsPostBack)
            {
                ProductName.Text = thisProduct.ProductName;
                if (thisProduct.UrlFriendly.Length > 0)
                {
                    ProductSlug.Text = thisProduct.UrlFriendly;
                }
                else
                {
                    ProductSlug.Text = GenerateUrlFriendlyName(thisProduct.ProductName);
                }
                ProductSku.Text = thisProduct.Sku;
                ShortDescription.Text = thisProduct.ShortDescription;
                //var tempTinyMce = (umbraco.editorControls.tinyMCE3.TinyMCE)FindControlRecursive(PaneDescription, "ShortDescription2");

                //tempTinyMce.Text = thisProduct.ShortDescription;
                OurPrice.Text = thisProduct.OurPrice.ToString();
                RetailPrice.Text = thisProduct.RetailPrice.ToString();

                // manufacturer
                ManufacturerCollection manufacturers = new ManufacturerCollection().OrderByAsc("Manufacturer").Load();
                Manufacturer.Items.Clear();
                foreach (Manufacturer thisMan in manufacturers)
                {
                    Manufacturer.Items.Add(new ListItem(thisMan.ManufacturerX, thisMan.ManufacturerID.ToString()));
                }
                Manufacturer.SelectedIndex = Manufacturer.Items.IndexOf(Manufacturer.Items.FindByValue(thisProduct.ManufacturerID.ToString()));

                // status
                ProductStatussCollection productStatus = new ProductStatussCollection().Load();
                Status.Items.Clear();
                foreach (ProductStatuss thisStatus in productStatus)
                {
                    Status.Items.Add(new ListItem(thisStatus.Status, thisStatus.StatusID.ToString()));
                }
                Status.SelectedIndex = Status.Items.IndexOf(Status.Items.FindByValue(thisProduct.StatusID.ToString()));

                // product type
                ProductTypesCollection productTypes = new ProductTypesCollection().Load();
                ProductType.Items.Clear();
                foreach (ProductTypes thisType in productTypes)
                {
                    ProductType.Items.Add(new ListItem(thisType.ProductType, thisType.ProductTypeID.ToString()));
                }
                ProductType.SelectedIndex = ProductType.Items.IndexOf(ProductType.Items.FindByValue(thisProduct.ProductTypeID.ToString()));

                // shipping type
                ShippingTypesCollection shippingTypes = new ShippingTypesCollection().Load();
                ShippingType.Items.Clear();
                foreach (ShippingTypes thisShipType in shippingTypes)
                {
                    ShippingType.Items.Add(new ListItem(thisShipType.ShippingType, thisShipType.ShippingTypeID.ToString()));
                }
                ShippingType.SelectedIndex = ShippingType.Items.IndexOf(ShippingType.Items.FindByValue(thisProduct.ShippingTypeID.ToString()));

                // shipping estimate
                ShippingEstimatesCollection shipEstimates = new ShippingEstimatesCollection().Load();
                ShipEstimate.Items.Clear();
                foreach (ShippingEstimates thisShipEstimate in shipEstimates)
                {
                    ShipEstimate.Items.Add(new ListItem(thisShipEstimate.ShippingEstimate, thisShipEstimate.ShipEstimateID.ToString()));
                }
                ShipEstimate.SelectedIndex = ShipEstimate.Items.IndexOf(ShipEstimate.Items.FindByValue(thisProduct.ShipEstimateID.ToString()));

                // tax type
                TaxTypeCollection taxTypes = new TaxTypeCollection().Load();
                TaxTypeDDL.Items.Clear();
                foreach (TaxType thisTaxType in taxTypes)
                {
                    TaxTypeDDL.Items.Add(new ListItem(thisTaxType.TaxTypeX, thisTaxType.TaxTypeID.ToString()));
                }
                TaxTypeDDL.SelectedIndex = TaxTypeDDL.Items.IndexOf(TaxTypeDDL.Items.FindByValue(thisProduct.TaxTypeID.ToString()));

                // currency code
                UtilCurrencyCollection currencyCodes = new UtilCurrencyCollection().Load();
                CurrencyCodeDDL.Items.Clear();
                foreach (UtilCurrency thisCurrency in currencyCodes)
                {
                    CurrencyCodeDDL.Items.Add(new ListItem(thisCurrency.Code, thisCurrency.CodeID.ToString()));
                }
                CurrencyCodeDDL.SelectedIndex = CurrencyCodeDDL.Items.IndexOf(CurrencyCodeDDL.Items.FindByValue(thisProduct.CurrencyCode));

                // weight
                Weight.Text = thisProduct.Weight.ToString();

                // dimensions - w, l h
                Width.Text = thisProduct.Width.ToString();

                Height.Text = thisProduct.Height.ToString();

                Length.Text = thisProduct.Length.ToString();

                foreach (ListItem listItem in DimensionUnitChooser.Items)
                {
                    if (String.Equals(listItem.Value, thisProduct.DimensionUnit, StringComparison.InvariantCultureIgnoreCase))
                    {
                        listItem.Selected = true;
                        break;
                    }
                }

                // Inventory
                Inventory.Text = thisProduct.Inventory.ToString();

                // List Order
                ListOrder.Text = thisProduct.ListOrder.ToString();

                //admin comments
                AdminComments.Text = thisProduct.AdminComments;

                // category
                CategoryCollection categories = new CategoryCollection().OrderByAsc("categoryName").Load();
                categoryDDL.Items.Clear();
                foreach (Category thisCat in categories)
                {
                    categoryDDL.Items.Add(new ListItem(thisCat.CategoryName, thisCat.CategoryID.ToString()));
                }
                if (thisProduct.GetCategoryCollection().Count > 0)
                    categoryDDL.SelectedIndex = categoryDDL.Items.IndexOf(categoryDDL.Items.FindByValue(thisProduct.GetCategoryCollection()[0].CategoryID.ToString()));

                categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
                categoryList.DataBind();

                // image media
                _mediaPicker.Value = thisProduct.DefaultImage;
                int mediaId;
                if (Int32.TryParse(_mediaPicker.Value.ToString(), out mediaId))
                {
                    if (mediaId > 0)
                    {
                        if (umbraco.cms.businesslogic.media.Media.IsNode(mediaId))
                        {
                            umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(mediaId);
                            if (m != null)
                            {
                                productImageView.ImageUrl = String.Format("/umbraco/ImageGen.ashx?image={0}&height=300&width=300&antialias=true&format=png&constrain=true", m.getProperty("umbracoFile").Value.ToString());
                            }
                        }
                    }
                }
                // other images
                ImageCollection prodImages = ProductController.GetImages(thisProduct.ProductID);
                if (prodImages.Count > 0)
                {
                    DataTable dt = prodImages.ToDataTable();

                    foreach (DataRow dr in dt.Rows)
                    {
                        int tempMediaId;
                        if (Int32.TryParse(dr["imageFile"].ToString(), out tempMediaId))
                        {
                            if (tempMediaId > 0)
                            {
                                if (umbraco.cms.businesslogic.media.Media.IsNode(tempMediaId))
                                {
                                    umbraco.cms.businesslogic.media.Media temp = new umbraco.cms.businesslogic.media.Media(tempMediaId);
                                    if (temp != null)
                                    {
                                        dr["imageFile"] = temp.getProperty("umbracoFile").Value.ToString();
                                    }
                                }
                            }
                        }
                    }

                    otherImagesList.DataSource = dt;
                    otherImagesList.DataBind();
                }

                // descriptors
                //rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
                //rptDescriptors.DataBind();

                // cross-sell
                ProductCollection prods = ProductController.GetAll().OrderByAsc(Product.Columns.ProductName);
                DataView prodView = prods.ToDataTable().DefaultView;
                prodView.Sort = Product.Columns.ProductName;

                ListItem item;
                chkProducts.Items.Clear();
                //JASON: Couldn't get it to sort, so used DataView
                //foreach (Product prod in prods)
                foreach (DataRowView prod in prodView)
                {
                    //item = new ListItem(prod.ProductName, prod.ProductID.ToString());
                    item = new ListItem(prod["ProductName"].ToString(), prod["ProductID"].ToString());
                    chkProducts.Items.Add(item);
                }
                // load the cross-sell products for this product
                ProductCollection crosses = PromotionService.GetCrossSells(thisProduct.ProductID).OrderByAsc("productName");
                currentCrossSellsPH.Controls.Clear();

                foreach (Product cross in crosses)
                {
                    foreach (ListItem l in chkProducts.Items)
                    {
                        if (int.Parse(l.Value) == cross.ProductID)
                        {
                            l.Selected = true;
                        }
                    }
                    currentCrossSellsPH.Controls.Add(new LiteralControl(String.Format("<div style=\"float: left; padding: 5px 40px 5px 0;\">{0}</div>", cross.ProductName)));
                }

                buildProductOptionsList();
            }

             
            // Main Tab Labels
                this.Pane1.Text = "Edit Product";
                this.pp_name.Text = "Product Name";
                this.pp_slug.Text = "URL Identifier";
                this.pp_sku.Text = "UPC";
                this.pp_our_price.Text = "Our Price";
                this.pp_retail_price.Text = "Retail Price";
                this.pp_manufacturer.Text = "Manufacturer";
                this.pp_status.Text = "Status";
                this.pp_product_type.Text = "ProductType";
                this.pp_shipping_type.Text = "Shipping Type";
                this.pp_ship_estimate.Text = "Ship Estimate";
                this.pp_tax_type.Text = "Tax Type";
                this.pp_stock_location.Text = "Stock Location";
                this.pp_weight.Text = "Weight";
                this.pp_width.Text = "Width";
                this.pp_height.Text = "Height";
                this.pp_length.Text = "Length";
                this.pp_dimension_unit.Text = "Dimension";
                this.pp_inventory.Text = "Inventory";
                this.pp_list_order.Text = "List Order";
                this.pp_currency_code.Text = "Currency Code";
                this.pp_admin_comments.Text = "Admin Comments";

                // Category Tab Labels
                this.Pane2.Text = "Product Categories";
                this.pp_categories.Text = "Category";
                this.pp_category_list.Text = "Assigned Categories";


                // Description Tab Labels
                this.PaneDescription.Text = "Product Description";
                this.pp_short_description.Text = "Description";

                //if (_tinymce != null)
                //{
                //    umbraco.uicontrols.TabView tabview = GetDashboardPanel();
                //    if (_tinymce.config["umbraco_toolbar_id"] != null)
                //        _tinymce.config.Remove("umbraco_toolbar_id");
                //    _tinymce.config.Add("umbraco_toolbar_id", tabview.ClientID + "_tab02layer_menu_sl");
                //}


                // Image Tab Labels
                this.Pane3.Text = "Product Image";
                this.pp_images.Text = "Default Product Image";
                this.pp_otherimages.Text = "Add Other Image";
                this.pp_otherimages_list.Text = "Other Product Images";

                // DescriptorTab Labels
                //this.Pane4.Text = "Product Descriptors";
                //this.pp_add_descriptor_list_order.Text = "List Order";
                //this.pp_add_descriptor_title.Text = "Title";
                //this.pp_add_descriptor_text.Text = "Text or List";
                //this.pp_descriptor_list.Text = "Descriptors";

                // AttributeTab Labels
                //this.Pane5.Text = "Product Attributes";

                // CrossSellTab Labels
                this.Pane6.Text = "Product Cross Sell Items";

                // Product Options
                this.pp_productOptions.Text = "Product Options";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private umbraco.uicontrols.TabView GetDashboardPanel()
        {
            umbraco.uicontrols.TabView tabview =
                (umbraco.uicontrols.TabView)FindControlRecursive(this.Page.Master, "tabControl");
            return tabview;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Root"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static Control FindControlRecursive(Control Root, string Id)
        {
            if (Root.ID == Id)
                return Root;

            foreach (Control Ctl in Root.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, Id);
                if (FoundCtl != null)
                    return FoundCtl;
            }

            return null;
        }

        private bool SaveProduct(string productName, string productId)
        {
            int prodId = -1;
            Product product;

            if (Int32.TryParse(productId, out prodId))
            {
                product = new Product("ProductID", prodId);
            }
            else
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0}", "Couldn't save product because productID is invalid."));

                return false;
            }

            Product.BeforeSaveProduct(product);

            decimal _OurPrice = 0;
            decimal _RetailPrice = 0;
            decimal _Weight = 0;
            decimal width;
            decimal height;
            decimal length;
            int _Inventory = -1;
            int _ListOrder = -1;
            int _manufacturerId;
            int _statusID;
            int _productTypeID;
            int _shippingTypeID;
            int _shipEstimateID;
            int _taxTypeID;

            try
            {
                product.ProductName = this.ProductName.Text;
                product.UrlFriendly = this.ProductSlug.Text;
                product.Sku = this.ProductSku.Text;
                product.ShortDescription = this.ShortDescription.Text;

                //var tempTinyMce = (umbraco.editorControls.tinyMCE3.TinyMCE)FindControlRecursive(PaneDescription, "ShortDescription2");
                //product.ShortDescription = tempTinyMce.Text;

                if (decimal.TryParse(this.OurPrice.Text, out _OurPrice))
                    product.OurPrice = _OurPrice;
                else
                    product.OurPrice = 0;
                if (decimal.TryParse(this.RetailPrice.Text, out _RetailPrice))
                    product.RetailPrice = _RetailPrice;
                else
                    product.RetailPrice = 0;
                product.ManufacturerID = Int32.TryParse(this.Manufacturer.SelectedItem.Value, out _manufacturerId) ? _manufacturerId : 0;
                product.StatusID = Int32.TryParse(this.Status.SelectedItem.Value, out _statusID) ? _statusID : 0;
                product.ProductTypeID = Int32.TryParse(this.ProductType.SelectedItem.Value, out _productTypeID) ? _productTypeID : 0;
                product.ShippingTypeID = Int32.TryParse(this.ShippingType.SelectedItem.Value, out _shippingTypeID) ? _shippingTypeID : 0;
                product.ShipEstimateID = Int32.TryParse(this.ShipEstimate.SelectedItem.Value, out _shipEstimateID) ? _shipEstimateID : 0;
                product.TaxTypeID = Int32.TryParse(this.TaxTypeDDL.SelectedItem.Value, out _taxTypeID) ? _taxTypeID : 0;
                product.CurrencyCode = this.CurrencyCodeDDL.SelectedItem.Value;
                if (decimal.TryParse(this.Weight.Text, out _Weight))
                    product.Weight = _Weight;
                else
                    product.Weight = 0;
                product.Width = Decimal.TryParse(Width.Text, out width) ? width : 0;
                product.Height = Decimal.TryParse(Height.Text, out height) ? height : 0;
                product.Length = Decimal.TryParse(Length.Text, out length) ? length : 0;
                product.DimensionUnit = DimensionUnitChooser.SelectedValue;
                if (int.TryParse(this.Inventory.Text, out _Inventory))
                    product.Inventory = _Inventory;
                else
                    product.Inventory = -1;
                if (int.TryParse(this.ListOrder.Text, out _ListOrder))
                    product.ListOrder = _ListOrder;
                else
                    product.ListOrder = 99;
                product.AdminComments = this.AdminComments.Text;

                // image
                if (_mediaPicker.Value != "")
                {
                    int _mediaID;
                    if (Int32.TryParse(_mediaPicker.Value, out _mediaID))
                    {
                        if (_mediaID > 0)
                        {
                            if (umbraco.cms.businesslogic.media.Media.IsNode(_mediaID))
                            {
                                umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(_mediaID);

                                if (m != null)
                                {
                                    product.DefaultImage = m.Id.ToString();
                                    //// also create a record in CSK_Store_Image - dashCommerce legacy requirement
                                    //Commerce.Common.Image img = new Commerce.Common.Image(true);
                                    //img.ImageFile = m.Id.ToString();
                                    //img.Caption = product.ProductName;
                                    //img.ProductID = product.ProductID;
                                    //ImageCollection productImages = new ImageCollection().Load();
                                    //productImages.Clear();
                                    //productImages.Add(img);
                                    //productImages.SaveAll("Commerce for Umbraco");
                                }
                            }
                        }
                    }
                }
                
                product.Save("Commerce for Umbraco");
                
                // cross sell
                Utility.SaveManyToMany("productID", product.ProductID, "CSK_Promo_Product_CrossSell_Map", "crossProductID", chkProducts.Items);
                
                Product.AfterSaveProduct(product);

                // load the cross-sell products for this product
                ProductCollection crosses = PromotionService.GetCrossSells(thisProduct.ProductID).OrderByAsc("productName");
                currentCrossSellsPH.Controls.Clear();
                foreach (Product cross in crosses)
                {
                    currentCrossSellsPH.Controls.Add(new LiteralControl(String.Format("<div style=\"float: left; padding: 5px 40px 5px 0;\">{0}</div>", cross.ProductName)));
                }

                return true;
            }
            catch (Exception e)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}",e.Message, e.StackTrace));
                
                return false;
            }
        }
        
        #region button handlers
        
        private void save_click(object sender, ImageClickEventArgs e)
        {
            if (this.SaveProduct(this.ProductName.Text, base.Request.QueryString["p"]))
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemSaved"), "");
            }
            else
            {
                base.ClientTools.ShowSpeechBubble(0, ui.Text("speechBubbles", "commerceItemErrorHeader"), ui.Text("speechBubbles", "commerceItemErrorText"));
            }
        }

        protected void categoryAddButton_Click(object sender, EventArgs e)
        {
            int value;
            if (Int32.TryParse(categoryDDL.SelectedItem.Value.ToString(), out value))
            {
                ProductController.AddToCategory(thisProduct.ProductID, value);
                categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
                categoryList.DataBind();
            }
        }

        protected void categoryList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string sCatID = e.CommandArgument.ToString();
            int value;
            if (Int32.TryParse(sCatID, out value))
            {
                ProductController.RemoveFromCategory(thisProduct.ProductID, value);
                categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
                categoryList.DataBind();
            }
        }

        private void buildProductOptionsList()
        {
            Commerce.Common.AttributeCollection productOptionItems = new Commerce.Common.AttributeCollection();
            productOptionItems.Where("ProductID", thisProduct.ProductID);
            productOptionItems.Load();

            DropDownListProductOptions.Items.Clear();

            AttributeTemplateCollection productOptionTemplates = new AttributeTemplateCollection().OrderByAsc("attributeName").Load();
            AttributeTemplateCollection productOptionTemplates_active = new AttributeTemplateCollection();

            for (int i = 0; i < productOptionTemplates.Count; i++)
            {
                // Check for existing option
                int ii = productOptionItems.Find("TemplateID", productOptionTemplates[i].TemplateID);
                if (ii == -1)
                {
                    DropDownListProductOptions.Items.Add(new ListItem(productOptionTemplates[i].AttributeName, productOptionTemplates[i].TemplateID.ToString()));
                }
                else
                {
                    productOptionTemplates_active.Add(productOptionTemplates[i]);
                }
            }

            if (productOptionTemplates_active.Count > 0)
            {
                DataTable dt = productOptionTemplates_active.ToDataTable();

                RepeaterProductOption.DataSource = dt;
                RepeaterProductOption.DataBind();
            }
        }

        protected void optionsAddButton_Click(object sender, EventArgs e)
        {
            Commerce.Common.Attribute productOptionLink = new Commerce.Common.Attribute();

            productOptionLink.ProductID = thisProduct.ProductID;
            productOptionLink.TemplateID = Int32.Parse(DropDownListProductOptions.SelectedValue);

            productOptionLink.Save();

            buildProductOptionsList();
        }

        protected void otherimagesAddButton_Click(object sender, EventArgs e)
        {
            if (_otherImagesMediaPicker.Value != "")
            {
                int value;
                if (Int32.TryParse(_otherImagesMediaPicker.Value, out value))
                {
                    if (value > 0)
                    {
                        if (umbraco.cms.businesslogic.media.Media.IsNode(value))
                        {
                            umbraco.cms.businesslogic.media.Media m = new umbraco.cms.businesslogic.media.Media(value);

                            if (m != null)
                            {
                                ImageCollection prodImagesTemp = ProductController.GetImages(thisProduct.ProductID);

                                // also create a record in CSK_Store_Image - dashCommerce legacy requirement
                                Commerce.Common.Image img = new Commerce.Common.Image(true);
                                img.ImageFile = m.Id.ToString();
                                img.Caption = thisProduct.ProductName;
                                img.ProductID = thisProduct.ProductID;
                                img.ListOrder = prodImagesTemp.Count + 1;
                                ImageCollection productImages = new ImageCollection().Load();
                                productImages.Clear();
                                productImages.Add(img);
                                productImages.SaveAll("Commerce for Umbraco");
                            }
                        }
                    }
                }
            }

            _otherImagesMediaPicker.Value = "";

            // rebind other images
            ImageCollection prodImages = ProductController.GetImages(thisProduct.ProductID);
            if (prodImages.Count > 0)
            {
                DataTable dt = prodImages.ToDataTable();

                foreach (DataRow dr in dt.Rows)
                {
                    int tempMediaId;
                    if (Int32.TryParse(dr["imageFile"].ToString(), out tempMediaId))
                    {
                        if (tempMediaId > 0)
                        {
                            if (umbraco.cms.businesslogic.media.Media.IsNode(tempMediaId))
                            {
                                umbraco.cms.businesslogic.media.Media temp = new umbraco.cms.businesslogic.media.Media(tempMediaId);

                                if (temp != null)
                                {
                                    dr["imageFile"] = temp.getProperty("umbracoFile").Value.ToString();
                                }
                            }
                        }
                    }
                }

                otherImagesList.DataSource = dt;
                otherImagesList.DataBind();
            }

            //ProductController.AddToCategory(thisProduct.ProductID, int.Parse(categoryDDL.SelectedItem.Value.ToString()));
            //categoryList.DataSource = CategoryController.GetByProductID(thisProduct.ProductID);
            //categoryList.DataBind();
        }

        protected string GetOptionList( string templateID )
        {
            StringBuilder sb = new StringBuilder();

            AttributeItemCollection productOptionItems = new AttributeItemCollection();
            productOptionItems.Where("TemplateID", Int32.Parse(templateID));
            productOptionItems.Load();

            for (int i = 0; i < productOptionItems.Count; i++)
            {
                sb.AppendFormat("{0}, ", productOptionItems[i].Name);
            }
            
            return sb.ToString();
        }

        protected string GetOptionType(string attributeTypeID)
        {

            AttributeTypesCollection productOptionTypes = new AttributeTypesCollection();
            productOptionTypes.Where("AttributeTypeID", Int32.Parse(attributeTypeID));
            productOptionTypes.Load();

            return productOptionTypes[0].AttributeType;
        }

        protected void productOptionList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                string productId = Request.QueryString.Get("p");
                string sTemplateID = e.CommandArgument.ToString();

                SubSonic.Query q = new SubSonic.Query("CSK_Store_Attribute");
                q.QueryType = SubSonic.QueryType.Delete;
                q.AddWhere("ProductID", productId);
                q.AddWhere("TemplateID", Int32.Parse(sTemplateID));
                q.Execute();

                buildProductOptionsList();
            }
            catch (Exception ex)
            {
                umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Error, umbraco.BusinessLogic.User.GetUser(0), -1, String.Format("{0} -- {1}", ex.Message, ex.StackTrace));
            }
        }

        protected void otherImagesList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            string sImageID = e.CommandArgument.ToString();

            if (e.CommandName == "delete")
            {
                // TODO: add to business logic
                Utility.DeleteManyToManyRecord("CSK_Store_Image", "productID", "imageID", thisProduct.ProductID, int.Parse(sImageID));
            }
            else    // re-order
            {
                Commerce.Common.Image imgToUpdate = Commerce.Common.Image.FetchByID(sImageID);

                imgToUpdate.SetColumnValue("listOrder", ((TextBox)e.Item.FindControl("otherImageOrder")).Text);
                imgToUpdate.SetColumnValue("caption", ((TextBox)e.Item.FindControl("otherImageCaption")).Text);
                imgToUpdate.Save("Commerce for Umbraco");
            }

            // rebind other images
            ImageCollection prodImages = ProductController.GetImages(thisProduct.ProductID);
            if (prodImages.Count > 0)
            {
                DataTable dt = prodImages.ToDataTable();

                foreach (DataRow dr in dt.Rows)
                {
                    int tempMediaId;
                    if (Int32.TryParse(dr["imageFile"].ToString(), out tempMediaId))
                    {
                        if (tempMediaId > 0)
                        {
                            if (umbraco.cms.businesslogic.media.Media.IsNode(tempMediaId))
                            {
                                umbraco.cms.businesslogic.media.Media temp = new umbraco.cms.businesslogic.media.Media(tempMediaId);

                                if (temp != null)
                                {
                                    dr["imageFile"] = temp.getProperty("umbracoFile").Value.ToString();
                                }
                            }
                        }
                    }
                }

                otherImagesList.DataSource = dt;
                otherImagesList.DataBind();
            }
        }

        protected void SaveDescriptorButton_Click(object sender, EventArgs e)
        {
            ProductDescriptor pd = new ProductDescriptor();
            try
            {
                pd.ListOrder = int.Parse(DescriptorListOrder.Text);
            }
            catch
            {
            }
            pd.Title = DescriptorTitle.Text;
            pd.Descriptor = DescriptorText.Text;
            pd.IsBulletedList = chkIsBulletedList.Checked;
            pd.ProductID = thisProduct.ProductID;
            pd.Save("Commerce for Umbraco");

            rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
            rptDescriptors.DataBind();
        }

        protected void rptDescriptors_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int descriptorID = 0;

            if (e.CommandArgument != null)
            {
                descriptorID = int.Parse(e.CommandArgument.ToString());
                if (e.CommandName == "delete")
                {
                    ProductDescriptor.Delete(descriptorID);
                }

                rptDescriptors.DataSource = ProductController.GetDescriptors(thisProduct.ProductID);
                rptDescriptors.DataBind();
            }
        }

        #endregion

        #region load routines
        protected override void OnInit(EventArgs e)
        {

            // Tab setup
            MainTab = tabControl.NewTabPage("Main");
            MainTab.Controls.Add(Pane1);

            ProductDescriptionTab = tabControl.NewTabPage("Description");
            ProductDescriptionTab.Controls.Add(PaneDescription);

            CategoryTab = tabControl.NewTabPage("Categories");
            CategoryTab.Controls.Add(Pane2);

            ImageTab = tabControl.NewTabPage("Images");
            ImageTab.Controls.Add(Pane3);

            //DescriptorTab = tabControl.NewTabPage("Descriptors");
            //DescriptorTab.Controls.Add(Pane4);

            ProductOptionsTab = tabControl.NewTabPage("Product Options");
            ProductOptionsTab.Controls.Add(Pane7);

            //AttributeTab = tabControl.NewTabPage("Attributes");
            //AttributeTab.Controls.Add(Pane5);

            CrossSellTab = tabControl.NewTabPage("Cross Sell");
            CrossSellTab.Controls.Add(Pane6);

            // Main Tab
            ImageButton save = MainTab.Menu.NewImageButton();
            save.Click += new ImageClickEventHandler(this.save_click);
            save.AlternateText = "Save";
            save.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Product Description Tab
            ImageButton save4 = ProductDescriptionTab.Menu.NewImageButton();
            save4.Click += new ImageClickEventHandler(this.save_click);
            save4.AlternateText = "Save";
            save4.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Category Tab
            ImageButton save2 = CategoryTab.Menu.NewImageButton();
            save2.Click += new ImageClickEventHandler(this.save_click);
            save2.AlternateText = "Save";
            save2.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Images Tab
            ImageButton save3 = ImageTab.Menu.NewImageButton();
            save3.Click += new ImageClickEventHandler(this.save_click);
            save3.AlternateText = "Save";
            save3.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // DescriptorTab
            //ImageButton save4 = DescriptorTab.Menu.NewImageButton();
            //save4.Click += new ImageClickEventHandler(this.save_click);
            //save4.AlternateText = "Save";
            //save4.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // AttributeTab
            //ImageButton save5 = AttributeTab.Menu.NewImageButton();
            //save5.Click += new ImageClickEventHandler(this.save_click);
            //save5.AlternateText = "Save";
            //save5.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // Product Options Tab
            ImageButton save7 = ProductOptionsTab.Menu.NewImageButton();
            save7.Click += new ImageClickEventHandler(this.save_click);
            save7.AlternateText = "Save";
            save7.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            // CrossSellTab
            ImageButton save6 = CrossSellTab.Menu.NewImageButton();
            save6.Click += new ImageClickEventHandler(this.save_click);
            save6.AlternateText = "Save";
            save6.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif";

            //Media Pickers
            _mediaPickerExtractor = new MediaPickerDataExtractor();
            _mediaPicker = new umbraco.editorControls.mediaChooser(_mediaPickerExtractor);
            _mediaPicker.ID = "mediapicker";
            pnlMediaPicker.Controls.Add(_mediaPicker);

            _otherImagesMediaPickerExtractor = new MediaPickerDataExtractor();
            _otherImagesMediaPicker = new umbraco.editorControls.mediaChooser(_otherImagesMediaPickerExtractor);
            _otherImagesMediaPicker.ID = "otherimagesmediapicker";
            pnlOtherImagesMediaPicker.Controls.Add(_otherImagesMediaPicker);

            //////////////// TinyMCE 


            //// get the blog doctype
            //umbraco.cms.businesslogic.web.DocumentType pageType = GetContentPageDocumentType();

            //// load all properties from the first tab
            //umbraco.cms.businesslogic.ContentType.TabI contentTab = pageType.getVirtualTabs[0];
            //foreach (umbraco.cms.businesslogic.propertytype.PropertyType pt in contentTab.PropertyTypes)
            //{
            //    umbraco.interfaces.IDataType dt = pt.DataTypeDefinition.DataType;

            //    // test for tinymce - we need to tell it to add icons to the dashboard menu
            //    if (dt.Id == new Guid("{5E9B75AE-FACE-41c8-B47E-5F4B0FD82F83}"))
            //    {
            //        _tinymce = (umbraco.editorControls.tinyMCE3.TinyMCE)dt.DataEditor;
            //        dt.DataEditor.Editor.ID = "ShortDescription2";
            //        umbraco.interfaces.IData df = pt.DataTypeDefinition.DataType.Data;

            //        blogpostControls.Controls.Add(dt.DataEditor.Editor);
            //    }
            //}



            base.Load += new EventHandler(this.Page_Load);
            this.InitializeComponent();
            base.OnInit(e);


        }

        private umbraco.cms.businesslogic.web.DocumentType GetContentPageDocumentType()
        {
            return umbraco.cms.businesslogic.web.DocumentType.GetByAlias("ContentPage");
        }

        private void InitializeComponent()
        {
        }
        #endregion

  
    }
}
